package org.magicbox.qjunTPO.config;

import org.magicbox.qjunTPO.Excepton.MyAccessDeniedHandler;
import org.magicbox.qjunTPO.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

@Configuration
public class SecuritityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyAccessDeniedHandler myAccessDeniedHandler;

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    PersistentTokenRepository persistentTokenRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.formLogin()//表单认证
                .loginProcessingUrl("/denglu")  //拦截这个请求 让其执行自定义登录逻辑
                //通过控制台的输出,发现该方法虽然在controller里有,但是并不执行 ,仅仅执行自定义的登录逻辑
                .loginPage("/toLogin")
                .successForwardUrl("/toSuccess")
//                .successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))
                .failureForwardUrl("/toFailure")
//                .failureHandler(new myAuthenticationFailureHandler("/error.html"))

                //自定义登录参数名
                .usernameParameter("username")
                .passwordParameter("password");


        http.csrf().disable();//关闭csrf防护

        http.authorizeRequests()//类似拦截器
                .antMatchers("/denglu").permitAll() //登录接口
                .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求
                .permitAll()

                .antMatchers("/toLogin","/toSuccess","/toFailure").permitAll()//登陆相关
                .antMatchers("/user/exPhone/*","/user/exStuid/*").permitAll()//用户表公共内容
                .antMatchers(HttpMethod.POST,"/user/add").permitAll()   //用户注册POST请求
//                .antMatchers("/js/**","/css/**","/images/**").permitAll()

                .antMatchers("/getImg/**").permitAll()   //文件上传预留映射虚拟路径

                .anyRequest()//除了之前配置了的所有请求,
                .authenticated();//必须登录之后被访问

        //异常处理
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler);

        http.rememberMe()
                //自定义登录逻辑
                .userDetailsService(userDetailsService)
                .rememberMeParameter("remember-me")//自定义参数名称
                //持久层对象,
                .tokenRepository(persistentTokenRepository)
                //设置多久不用登录,默认两周,现在设置成60秒
                .tokenValiditySeconds(60);

        //允许跨域
        http.cors();
    }


}
